<?php
namespace Home\Biz;

class OrderBiz{
    /**
     * 生成英雄会O2O订单编号
     * @return string
     */
	public static function generateOrderId(){
		$seq = 10000000 + CommonBiz::getNewOrderSeq('order_seq');
		return 'SO'.$seq;
	}

    /**
     * 生成等级品订单编号
     * @return string
     */
    public static function generateDJPOrderId(){
        $seq = 10000000 + CommonBiz::getNewOrderSeq('order_seq');
        return 'DJP'.$seq;
    }
	
	
	/**
	 * ================  Address相关 Begin  ================
	 */
	
	public static function addAddress($post, $user_id, $address_id){
		// 数据校验start
		if(empty($post['consignee_name'])){
			return '姓名不能为空';
		}
	
		if(empty($post['consignee_cellphone'])){
			return '手机不能为空';
		}
	
		if(!StringBiz::isCellphone($post['consignee_cellphone'])){
			return '手机格式不符合';
		}
		
		if(!empty($post['consignee_zip'])){
			if(!StringBiz::isZipcode($post['consignee_zip'])){
				return '邮编格式不符合';
			}
		}
		
		
		if(!empty($post['consignee_tel'])){
			if(!StringBiz::isPhone($post['consignee_tel'])){
				return '电话格式不符合';
			}
		}
		
		
		if(empty($post['district_id'])){
			return '省市区不能为空';
		}
	
		if(empty($post['consignee_address'])){
			return '地址不能为空';
		}
		
		if(!StringBiz::isAddress($post['consignee_address'])){
			return '地址信息不正确';
		}
		$user_info = M('userInfo', '', 'DB_trade')->where('user_id = "%s"', array($user_id))->find();
		if(empty($user_info)){
			return '用户不存在';
		}
		//省市区
		$district_id = $post['district_id'];
		$lst_region_en = M('', '', 'DB_system')->query("
				SELECT * FROM province p
				INNER JOIN city c
				ON p.`province_id` = c.`province_id`
				INNER JOIN district d
				ON c.`city_id` = d.`city_id`
				WHERE district_id = '%s'
				", $district_id);
	
	
		if(empty($lst_region_en)){
			return '错误的区域选择';
		}
		else{
			$region_en = $lst_region_en[0];
		}
		// 数据校验end
	
		//添加user_info
// 		$user_en = array();
// 		$user_id= UserBiz::generateUserId();
// 		$user_en['user_id']			= $user_id;
// 		$user_en['user_name']		= $post['consignee_name'];
// 		$user_en['real_name']		= $post['consignee_name'];
// 		$user_en['cellphone']		= $post['consignee_cellphone'];
// 		$user_en['phone']			= $post['consignee_tel'];
// 		$user_en['account_source']	= 5;
	
// 		$user_en['province_id']		= $region_en['province_id'];
// 		$user_en['province_name']	= $region_en['province_name'];
// 		$user_en['city_id']			= $region_en['city_id'];
// 		$user_en['city_name']		= $region_en['city_name'];
// 		$user_en['district_id']		= $region_en['district_id'];
// 		$user_en['district_name']	= $region_en['district_name'];
// 		$user_en['address']			= $post['consignee_address'];
// 		$user_en['register_date']	= date("y-m-d H:i:s", time());
// 		$user_en['register_source']	= 5;
// 		$user_en['status']			= 1;
	
// 		$user_en['create_user']	= 'whaleyFZ.AjaxService.order.addAddress';
// 		$user_en['create_date']	= date("y-m-d H:i:s", time());
// 		M('userInfo', '', 'DB_trade')->add($user_en);
	
		//添加user_address
		$user_address_en = array();
	
		$user_address_en['address_id']		= $address_id;
		$user_address_en['user_id']			= $user_id;
		$user_address_en['consignee_name']		= $post['consignee_name'];
		$user_address_en['consignee_cellphone']	= $post['consignee_cellphone'];
		$user_address_en['consignee_tel']		= $post['consignee_tel'];
		$user_address_en['consignee_province_id']	= $region_en['province_id'];
		$user_address_en['consignee_province']		= $region_en['province_name'];
		$user_address_en['consignee_city_id']		= $region_en['city_id'];
		$user_address_en['consignee_city']			= $region_en['city_name'];
		$user_address_en['consignee_district_id']	= $region_en['district_id'];
		$user_address_en['consignee_district']	= $region_en['district_name'];
		$user_address_en['consignee_address']	= $post['consignee_address'];
		$user_address_en['consignee_zip']		= $post['consignee_zip'];
		$user_address_en['create_user']	= 'whaleyFZ.AjaxService.order.addAddress';
		$user_address_en['create_date']	= date("y-m-d H:i:s", time());
		M('userAddress', '', 'DB_trade')->add($user_address_en);
	}
	
	public static function updateAddress($post, $address_id){
		// 数据校验start
		if(empty($post['consignee_name'])){
			return '姓名不能为空';
		}
		
		if(empty($post['consignee_cellphone'])){
			return '手机不能为空';
		}
		
		if(!StringBiz::isCellphone($post['consignee_cellphone'])){
			return '手机格式不符合';
		}
		
		if(!empty($post['consignee_zip'])){
			if(!StringBiz::isZipcode($post['consignee_zip'])){
				return '邮编格式不符合';
			}
		}
		
		
		if(!empty($post['consignee_tel'])){
			if(!StringBiz::isPhone($post['consignee_tel'])){
				return '电话格式不符合';
			}
		}
		
		
		if(empty($post['district_id'])){
			return '省市区不能为空';
		}
		
		if(empty($post['consignee_address'])){
			return '地址不能为空';
		}
		
		if(!StringBiz::isAddress($post['consignee_address'])){
			return '地址信息不正确';
		}
		
		
		
		// 数据校验begin
		$user_address_en = M('userAddress', '', 'DB_trade')->where("address_id='%s'", $address_id)->find();
		if(empty($user_address_en)){
			return '不存在的地址编号';
		}
		// 数据校验end
	
		//省市区
		$district_id = $post['district_id'];
		$lst_region_en = M('', '', 'DB_system')->query("
				SELECT * FROM province p
				INNER JOIN city c
				ON p.`province_id` = c.`province_id`
				INNER JOIN district d
				ON c.`city_id` = d.`city_id`
				WHERE district_id = '%s'
				", $district_id);
	
	
		if(empty($lst_region_en)){
			return '错误的区域选择';
		}
		else{
			$region_en = $lst_region_en[0];
		}
		// 数据校验end
		
	
		$user_address_en = array();
	
		$user_address_en['address_id']			= $address_id;
        $user_address_en['consignee_name']		= $post['consignee_name'];
		$user_address_en['consignee_cellphone']	= $post['consignee_cellphone'];
		$user_address_en['consignee_tel']		= $post['consignee_tel'];
		$user_address_en['consignee_province_id']	= $region_en['province_id'];
		$user_address_en['consignee_province']		= $region_en['province_name'];
		$user_address_en['consignee_city_id']		= $region_en['city_id'];
		$user_address_en['consignee_city']			= $region_en['city_name'];
		$user_address_en['consignee_district_id']	= $region_en['district_id'];
		$user_address_en['consignee_district']	= $region_en['district_name'];
		$user_address_en['consignee_address']	= $post['consignee_address'];
		$user_address_en['consignee_zip']		= $post['consignee_zip'];
		$user_address_en['update_user']			= 'whaleyFZ.AjaxService.order.addAddress';
		$user_address_en['update_date']			= date("y-m-d H:i:s", time());
	
		M('userAddress', '', 'DB_trade')->where("address_id='$address_id'")->save($user_address_en);
	}
	
	
	/**
	 * 计算购物车商品金额
     * 运用促销规则
     * 计算运费（暂无）
     * 并返回购物车商品明细(包括金额运费促销数量等)
	 */
	public static function calcCart($lst_sku_str){
		
		$goods_amount		= 0;
        $goods_qty		    = 0;
		$promotion_amount	= 0;
        $freight            = 0;
        $no_freight_order_amount  = 0;
        $order_amount       = 0;

		
		// ============= 计算sku金额和数量 begin =============
        $lst_param_sku = array();
        $lst_buy_sku_id = array();
		$lst_sku_str_array = explode('|', $lst_sku_str);
		foreach($lst_sku_str_array as $sku_str){
			$sku_str_array = explode(',', $sku_str);
			$sku = array(
					'sku_id'=> $sku_str_array[0],
					'qty'	=> $sku_str_array[1]
			);
			array_push($lst_param_sku, $sku);
			array_push($lst_buy_sku_id, $sku['sku_id']);
		}

		$lst_sku_en = M('sku', '', 'DB_product')
		->where("sku_channel IN(5, 13) AND status = 1 AND sku_id IN('".implode("','", $lst_buy_sku_id)."')")
		->select();
		
		foreach($lst_sku_en as $key => $sku_en){
			$curr_sku_id = $sku_en['sku_id'];

			$lst_filter_param_sku = array_filter($lst_param_sku,
					function($item) use ($curr_sku_id) {
						return $item['sku_id'] == $curr_sku_id;
					});
			if(empty($lst_filter_param_sku)){
				continue;
			}
			$curr_sku_en   			    = current($lst_filter_param_sku);
			$lst_sku_en[$key]['qty']    = $curr_sku_en['qty'];


            $lst_sku_en[$key]['image']  = C('UriConfig.sku_image_450_pre_url').$lst_sku_en[$key]['image'];
			$goods_amount         	    = $goods_amount + $sku_en['sale_price'] * $curr_sku_en['qty'];
            $goods_qty			        = $goods_qty + $curr_sku_en['qty'];
		}

        // ============= 计算sku金额和数量 end =============


		// ============= 计算促销金额 begin =============
        $lst_promotion_en   = M('promotion','','DB_product')
            ->where('promotion_channel=5 AND promotion_type=1 AND status=1')->order('discount_amount DESC')
            ->select();


        $curr_promotion_en   = null;
        foreach($lst_promotion_en as $promotion_en){
            $promotion_sku_amount   = 0;
            foreach($lst_sku_en as $sku_en){
                $curr_sku_id    = $sku_en['sku_id'];

                //判断当前sku是否支持促销
                $str_select_flag= strstr($promotion_en['sku_id_list'], $curr_sku_id);
                if(empty($promotion_en['sku_id_list'])){
                    $str_select_flag = true;
                }

                if(!empty($str_select_flag)){
                    $promotion_sku_amount   = $promotion_sku_amount + intval($sku_en['qty']) * floatval($sku_en['sale_price']);
                }
            }

            //判断是否满足满减条件
            if($promotion_sku_amount >= $promotion_en['condition_amount']) {
                $curr_promotion_en = $promotion_en;
                break;
            }
        }
        if(!empty($curr_promotion_en)){
            $promotion_amount = $curr_promotion_en['discount_amount'];
        }
        // ============= 计算促销金额 end =============


        // ============= 计算运费金额 begin =============
        $freight    = 0;
        // ============= 计算运费金额 end =============


        // ============= 计算订单金额 begin =============
        $no_freight_order_amount  = $goods_amount - $promotion_amount;
        $order_amount       = $no_freight_order_amount + $freight;
        // ============= 计算订单金额 end =============

        $return_array   = array(
            'goods_qty'     => $goods_qty,
            'goods_amount'  => $goods_amount,
            'promotion_en'  => $curr_promotion_en,
            'promotion_amount'  => $promotion_amount,
            'freight'           => $freight,
            'no_freight_order_amount'=> $no_freight_order_amount,
            'order_amount'  => $order_amount,
            'lst_sku_en'    => $lst_sku_en
        );

        return $return_array;
	}
	
	/**
	 * ================  Address相关 End  ================
	 */
	
	
	
	/**
	 * ================  Order相关 Begin  ================
	 */
	
	
	/**
	 * 
	 * @param unknown $promoter_id
	 * @param unknown $type 1,所有订单；2，未分成订单；3，已分成订单
	 * @param unknown $index
	 * @param unknown $size
	 */
	public static function getOrderList($promoter_id, $type, $index, $size){
		// 1、参数校验begin
		if(empty($type)){
			$type = 1;
		}
		
		if(empty($index)){
			$index = 1;
		}
		
		if(empty($size)){
			$size = C('OrderConfig.order_list_size');
		}
		
		if(empty($promoter_id)){
			return '不存在用户id';
		}
		
		$promoter_en = M('promoterInfo')->where("promoter_id='%s'", $promoter_id)->find();

		if(empty($promoter_en)){
			return '不存在的用户';
		}
		// 1、参数校验end
		
		// 2、获取不同分类的订单start
		$lst_promoterOrder_en = array();
		switch($type){
			case 1:
				//所有订单
				$lst_promoterOrder_en = M('promoterOrder')->where("promoter_id='%s'", $promoter_id)
				->order("create_date DESC")->page($index, $size)
				->select();
				break;
			case 2:
				//未分成订单
				$lst_promoterOrder_en = M('promoterOrder')->where("promoter_id='%s' AND order_revenue_status IN (0, 2)", $promoter_id)
				->order("create_date DESC")->page($index, $size)
				->select();
				break;
			case 3:
				//已分成订单
				$lst_promoterOrder_en = M('promoterOrder')->where("promoter_id='%s' AND order_revenue_status=3", $promoter_id)
				->order("create_date DESC")->page($index, $size)
				->select();
				break;
			case 4:
				//未支付订单
				$lst_promoterOrder_en = M('promoterOrder')->where("promoter_id='%s' AND payment_status=0", $promoter_id)
				->order("create_date DESC")->page($index, $size)
				->select();
				break;
			default:
				//所有订单
				$lst_promoterOrder_en = M('promoterOrder')->where("promoter_id='%s'", $promoter_id)
				->order("create_date DESC")->page($index, $size)
				->select();
				break;
		}

		foreach($lst_promoterOrder_en as $key => $promoterOrder_en){
			$lst_promoterOrder_en[$key]['order_revenue_status_text'] = StringBiz::getPromoterOrderRevenueStatusText($promoterOrder_en['order_revenue_status']);
			$lst_promoterOrder_en[$key]['order_status_text'] = StringBiz::getPromoterOrderRevenueStatusText($promoterOrder_en['order_status']);
		}
		// 2、获取不同分类的订单end
		
		return $lst_promoterOrder_en;
	}
	
	public static function searchOrder($keyword){
		$lst_order_en = M('orderInfo', '', 'DB_trade')
		->where("buyer_mobile='%s' OR order_id='%s'", array($keyword, $keyword))
		->select();
		
		return $lst_order_en;
	}
	
	
	public static function cancelOrder($order_id, $user){
		//0. 数据校验
		if(empty($order_id)){
			return '不存在订单编号';
		}
		$order_en = M('orderInfo', '', 'DB_trade')
		->where("order_id='%s' AND order_type=5", $order_id)
		->find();
		if(empty($order_en)){
			return '不存在的订单';
		}
		
		if(in_array($order_en['payment_status'], array(1,2,3))){
			return '订单已经支付或退款，无法取消！';
		}
		//0. 数据校验
		
		//1. 更新order_info
		M('orderInfo', '', 'DB_trade')->where("order_id='%s'",$order_id)->setField('order_status', 51);
		//2.写入order_status_change_log
		$order_status_change_log = array(
				'order_id'		=> $order_id,
				'order_status'	=> 51,
				'order_status_text'	=> '用户取消',
				'remark'		=> '',
				'create_user'	=> $user,
				'create_date'	=> date("y-m-d H:i:s", time()),
		);
		M('orderStatusChangeLog', '', 'DB_trade')->add($order_status_change_log);
		
		
		
		//3.写入order_cancel
		$order_cancel_en = array(
				'order_id'		=> $order_id,
				'role_type'		=> 1,
				'role_user_id'	=> $order_en['user_id'],
				'cancel_reason'	=> 1,
				'remark'		=> '',
				'create_user'	=> $user,
				'create_date'	=> date("y-m-d H:i:s", time()),
		);
		M('orderCancel', '', 'DB_trade')->add($order_cancel_en);
		
		//4.联动更新promoter_order表的订单状态
		M('promoterOrder')->where("order_id='%s'", $order_id)->setField('order_status', 51);
		
	}
	
	/**
	 * ================  Order相关 End  ================
	 */
	
	
	/*
	 * #########################################################
	 * 提交订单 BEGIN
	 * #########################################################
	 */
	
	/**
	 * 提交订单
	 * @param unknown $address_id
	 * @param unknown $lst_sku
	 */
	public static function submitOrder($address_id, $lst_sku, $order_id){

		//region 1、提交订单参数校验
		if(empty($address_id)){
			return array(
			    'is_success'    => 0,
                'msg'           => '未输入地址'
            );
		}
		
		if(empty($lst_sku)){
            return array(
                'is_success'    => 0,
                'msg'           => '没有购买的商品'
            );
		}
		
		$share_code = cookie(C('AdminConfig.share_code_cookie_name'));
		if(empty($share_code)){
            return array(
                'is_success'    => 0,
                'msg'           => '没有推荐码'
            );
		}
		
		$promoter_en = M('promoterInfo')->where("share_code='%s'", $share_code)->find();
		if(empty($promoter_en)){
            return array(
                'is_success'    => 0,
                'msg'           => '不存在推荐人'
            );
		}
		
		$user_address_en = M('userAddress', '', 'DB_trade')->where("address_id='%s'", $address_id)->find();
		if(empty($user_address_en)){
            return array(
                'is_success'    => 0,
                'msg'           => '不存在的地址编号'
            );
		}
		
		$recive_district_id	= $user_address_en['consignee_district_id']; 
		$rrsShippingRegion_en	= M('rrsShippingRegion', '', 'DB_trade')->where("recive_district_id = '%s' AND warehouse_code IS NOT NULL", $recive_district_id)->find();
		if(empty($rrsShippingRegion_en)){
            return array(
                'is_success'    => 0,
                'msg'           => '您填写的地址暂不支持配送'
            );
        }

        $order_type = 5;
		//endregion 1、提交订单参数校验

		
		// 计算购物车商品列表和金额
		$lst_sku_str    = $lst_sku;
        $cart_en        = OrderBiz::calcCart($lst_sku_str);
        $lst_buy_sku    = $cart_en['lst_sku_en'];

        //region 等级品业务逻辑
        //标记是否是等级品订单
        $is_grade_product   = false;
        $sku_channel_array  = array();
        foreach($lst_buy_sku as $buy_sku_en) {
            if(!in_array($buy_sku_en['sku_channel'], $sku_channel_array)){
                array_push($sku_channel_array, $buy_sku_en['sku_channel']);
            }
        }

        if(count($sku_channel_array) > 1){
            return array(
                'is_success'    => 0,
                'msg'           => '等级品不可与其它商品一起下单'
            );
        }

        if(current($sku_channel_array) == 13){
            $is_grade_product   = true;
            $order_type         = 13;

            $order_id           = OrderBiz::generateDJPOrderId();

            //每位员工只能购买一件等级品
            if($cart_en['goods_qty'] > 1){
                return array(
                    'is_success'    => 0,
                    'msg'           => '等级品每次只能购买一件'
                );
            }

            if($promoter_en['promoter_id'] != 'PR822010'){
                $already_buy_qty    = M('order_info', '', 'DB_trade')->where("order_type=13 AND `seller_alipay_no`='%s'", $promoter_en['promoter_id'])->sum('goods_qty');
                if($already_buy_qty > 0){
                    return array(
                        'is_success'    => 0,
                        'msg'           => '每位员工仅限购买一件等级品'
                    );
                }
            }
        }
        //endregion 等级品业务逻辑


		//写入order_detail 和 rrs出库单表 begin
		$oid_num    = 100;
        $order_date	= date("y-m-d H:i:s", time());
		foreach($lst_buy_sku as $buy_sku_en){
			
			//写入order_detail
			$third_oid = $order_id.strval($oid_num);
			$order_detail_en = OrderBiz::insertOrderDetail($order_id, $third_oid, $buy_sku_en);
			
			//写入promoter_order_detail
			OrderBiz::insertPromoterOrderDetail($order_id, $third_oid, $buy_sku_en);
			
			//写入rrs_stock_order
			OrderBiz::insertRrsStockOrder($order_id, $third_oid, $order_date, $buy_sku_en, $user_address_en, $rrsShippingRegion_en, $promoter_en);
			
			$oid_num = $oid_num + 1;
		}
		//写入order_detail 和 rrs出库单表  end
		
		
		//写入order_info begin
		$payment_amount = $cart_en['order_amount'];
		$order_info_en = array(
				'order_id'	=> $order_id,
				'order_status'	=> 10,
				//'order_revenue_status' => 0,
				'order_type'	=> $order_type,
				'payment_type'	=> 2,
				'payment_method'=> 21,
				'payment_status'=> 0,
				'user_id'		=> $user_address_en['user_id'],
				'seller_alipay_no'	=> $promoter_en['promoter_id'],
				'seller_name'		=> $promoter_en['promoter_name'],
				'buyer_name'	=> $user_address_en['consignee_name'],
				'buyer_mobile'	=> $user_address_en['consignee_cellphone'],
				'buyer_ip'		=> get_client_ip(),
				'invoice_kind'	=> 21,
				'invoice_status'=> 1,
				'invoice_name'	=> '个人',
				'address_id'	=> $address_id,
				'consignee_name'=>  $user_address_en['consignee_name'],
				'consignee_cellphone'	=>  $user_address_en['consignee_cellphone'],
				'consignee_province_id'	=>  $user_address_en['consignee_province_id'],
				'consignee_province'	=>  $user_address_en['consignee_province'],
				'consignee_city_id'		=>  $user_address_en['consignee_city_id'],
				'consignee_city'		=>  $user_address_en['consignee_city'],
				'consignee_district_id'	=>  $user_address_en['consignee_district_id'],
				'consignee_district'	=>  $user_address_en['consignee_district'],
				'consignee_address'		=>  $user_address_en['consignee_address'],
				'consignee_zip'	=>  $user_address_en['consignee_zip'],
				'goods_amount'	=>  $cart_en['goods_amount'],
				'goods_qty'		=>  $cart_en['goods_qty'],
				'actual_payment'=>	0,
				'payment_amount'=>  $payment_amount,
				'freight'		=>  $cart_en['freight'],
				'discount_fee'	=>	$cart_en['promotion_amount'],
				'order_amount'	=>  $cart_en['order_amount'],
				'cash_back_status'		=> 1,
				'order_date'	=>  $order_date,
				'create_user'	=> 'whaleyFZ.AjaxService.order.submitOrder',
				'create_date'	=>	date("y-m-d H:i:s", time()),
		);
		M('orderInfo', '', 'DB_trade')->add($order_info_en);
		//写入order_info end
		
		
		//写入order_status_change_log begin
		$order_status_change_log = array(
				'order_id'		=> $order_id,
				'order_status'	=> 10,
				'order_status_text'	=> '已提交',
				'remark'		=> '',
				'create_user'	=> 'whaleyFZ.AjaxService.order.submitOrder',
				'create_date'	=> date("y-m-d H:i:s", time()),
		);
		M('orderStatusChangeLog', '', 'DB_trade')->add($order_status_change_log);
		//写入order_status_change_log end
		
		
		//写入order_discount（暂无）
        $promotion_en   = $cart_en['promotion_en'];
		if(!empty($promotion_en)){
			$order_discount_en = array(
					'order_id'		=> $order_id,
					'third_order_id'=> $order_id,
					'discount_type'	=> 51,
					'discount_name' => $promotion_en['promotion_name'],
					'discount_desc' => $promotion_en['promotion_desc'],
					'discount_amount'	=> $cart_en['promotion_amount'],
					'create_user'	=> 'whaleyFZ.AjaxService.order.submitOrder',
					'create_date'	=> date("y-m-d H:i:s", time()),
			);
		}
		
		
		//写入order_payment
		$order_payment_en = array(
				'order_id'		=> $order_id,
				'payment_type'	=> 2,
				'payment_method'=> 21,
				'payment_status'=> 0,
				'freight'		=> 0,
				'payment_amount'=> $payment_amount,
				'create_user'	=> 'whaleyFZ.AjaxService.order.submitOrder',
				'create_date'	=> date("y-m-d H:i:s", time()),
		);
		M('orderPayment', '', 'DB_trade')->add($order_payment_en);
		
		
		//写入promoter_order，用于分成begin
		$promoter_order_en = array(
				'promoter_id'	=> $promoter_en['promoter_id'],
				'promoter_name'	=> $promoter_en['promoter_name'],
				'promoter_type'	=> $promoter_en['promoter_type'],
				'order_revenue_status' => 0,
				'share_code'	=> $promoter_en['share_code'],
				'order_id'		=> $order_id,
				'order_type'	=> $order_type,
				'order_status'	=> 10,
				'order_revenue_status'	=> 0,
				'payment_status'=> 0,
				'order_amount'	=> $cart_en['order_amount'],
				'order_date'	=> $order_date,
				'status'		=> 1,
				'create_user'	=> 'whaleyFZ.AjaxService.order.submitOrder',
				'create_date'	=> date("y-m-d H:i:s", time()),
		);
		M('promoter_order')->add($promoter_order_en);
		//写入promoter_order，用于分成end

        return array(
            'is_success'    => 1,
            'msg'           => $order_id
        );
	}
	
	/**
	 * @param unknown $order_id 订单编号
	 * @param unknown $third_oid 第三方子订单编号（对应order_detail表同字段）
	 * @param unknown $buy_sku_en 购买的sku的信息
	 */
	public static function insertOrderDetail($order_id, $third_oid, $buy_sku_en){
		$order_detail_en = array(
				'oid'		=> $third_oid,
				'order_id'	=> $order_id,
				'third_oid'	=> $third_oid,
				'style_id'	=> $buy_sku_en['style_id'],
				'style_name'=> $buy_sku_en['style_name'],
				'sku_id'	=> $buy_sku_en['sku_id'],
				'third_sku_id'			=> $buy_sku_en['sku_sn'],
				'qty'					=> $buy_sku_en['qty'],
				'market_price'			=> $buy_sku_en['market_price'],
				'sale_price'			=> $buy_sku_en['sale_price'],
				'image'					=> $buy_sku_en['image'],
				'payment_amount'		=> $buy_sku_en['qty'] * $buy_sku_en['sale_price'],
				'create_user'			=> 'whaleyFZ.AjaxService.order.submitOrder',
				'create_date'			=> date("y-m-d H:i:s", time()),
		);
		M('orderDetail', '', 'DB_trade')->add($order_detail_en);
		return $order_detail_en;
	}

	
	/**
	 * 写入promoter_order_detail表
	 * @param unknown $order_id 订单编号
	 * @param unknown $third_oid 第三方子订单编号（对应order_detail表同字段）
	 * @param unknown $buy_sku_en 购买的sku的信息
	 */
	public static function insertPromoterOrderDetail($order_id, $third_oid, $buy_sku_en){
		$promoterOrderDetail_en = array(
				'oid'	=> $third_oid,
				'order_id'	=> $order_id,
				'qty'		=> $buy_sku_en['qty'],
				'style_id'	=> $buy_sku_en['style_id'],
				'style_name'=> $buy_sku_en['style_name'],
				'sku_id'	=> $buy_sku_en['sku_id'],
				'sku_name'	=> $buy_sku_en['sku_name'],
				'person_commission_amount'	=> $buy_sku_en['person_commission_amount'],
				'dealer_commission_amount'	=> $buy_sku_en['dealer_commission_amount'],
				'create_user'			=> 'whaleyFZ.AjaxService.order.submitOrder',
				'create_date'			=> date("y-m-d H:i:s", time()),
		);
		M('promoterOrderDetail')->add($promoterOrderDetail_en);
	}
	
	
	/**
	 * 向rrs_stock_order写入数据
	 * @param unknown $order_id 订单编号
	 * @param unknown $third_oid 第三方子订单编号（对应order_detail表同字段）
	 * @param unknown $buy_sku_en 购买的sku的信息
	 * @param unknown $user_address_en 收货人的地址信息
	 * @param unknown $rrsShippingRegion_en rrs配送地址信息
	 */
	public static function insertRrsStockOrder($order_id, $third_oid, $order_date, $buy_sku_en, $user_address_en, $rrsShippingRegion_en, $promoter_en){
		
		$rrs_stock_order_id = ''.$third_oid;
		$insertRrs_stock_order_add = array(
				'rrs_stock_order_id'	=>	$rrs_stock_order_id,
				'order_id'				=>	$order_id,
				'third_oid'				=>	$third_oid,
				'promoter_id'			=> 	$promoter_en['promoter_id'],
				'promoter_name'			=> 	$promoter_en['promoter_name'],
				'order_date'			=>  $order_date,
				'order_type'			=>  5,
				'rrs_stock_order_type'	=>	1,
				'cod_amount'			=>	0,
				'consignee_name'		=>	$user_address_en['consignee_name'],
				'consignee_cellphone'	=>	$user_address_en['consignee_cellphone'],
				'consignee_tel'			=> '',
				'consignee_province_id'	=>  $rrsShippingRegion_en['recive_province_id'],
				'consignee_province'	=>  $rrsShippingRegion_en['recive_province_name'],
				'consignee_city_id'		=>  $rrsShippingRegion_en['recive_city_id'],
				'consignee_city'		=>  $rrsShippingRegion_en['recive_city_name'],
				'consignee_district_id'	=>  $rrsShippingRegion_en['recive_district_id'],
				'consignee_district'	=>  $rrsShippingRegion_en['recive_district_name'],
				'consignee_address'		=>	$user_address_en['consignee_address'],
				'material_no'			=>	$buy_sku_en['material_no'],
				'goods_qty'				=>	$buy_sku_en['qty'],
				'batch'					=>	'正品',
				'send_warehouse_code'	=>	$rrsShippingRegion_en['warehouse_code'],
				'send_warehouse_name'	=>	$rrsShippingRegion_en['warehouse_name'],
				'create_user'			=> 'whaleyFZ.AjaxService.order.submitOrder',
				'create_date'			=> date("y-m-d H:i:s", time())
		);
		M('rrsStockOrder', '', 'DB_trade')->add($insertRrs_stock_order_add);
	}
	
	
	/*
	 * #########################################################
	 * 提交订单 END
	 * #########################################################
	 */
	
	
	
	
	/**
	 * 
	 * @param unknown $order_en
	 * @return 生成向支付宝提交的请求html
	 */
	public static function generateAlipayRequestHtml($order_en){
		$alipay_config = array();
		$alipay_config = C('AlipayConfig');


        //商户订单号
        $out_trade_no = $order_en['order_id'];
        //付款金额
        $total_fee = $order_en['order_amount'];
        //商品展示地址
        $show_url = 'http://o.whaley.cn/buy/cart';

        //订单名称
        $subject = '订单编号：'.$order_en['order_id'];
        //订单描述
        $body    = '订单编号：'.$order_en['order_id'];

        if($order_en['order_type'] == 5){
            //订单名称
            $subject = '英雄会订单编号：'.$order_en['order_id'];
            //订单描述
            $body    = '英雄会订单编号：'.$order_en['order_id'];
        }

        if($order_en['order_type'] == 13){
            //订单名称
            $subject = '等级品订单编号：'.$order_en['order_id'];
            //订单描述
            $body    = '等级品订单编号：'.$order_en['order_id'];
        }

		
		//构造要请求的参数数组，无需改动
		$parameter = array(
				"service"       => $alipay_config['service'],
				"partner"       => $alipay_config['partner'],
				"seller_id"  	=> $alipay_config['seller_id'],
				"payment_type"	=> $alipay_config['payment_type'],
				"notify_url"	=> $alipay_config['notify_url'],
				"return_url"	=> $alipay_config['return_url'],
				"_input_charset"=> trim(strtolower($alipay_config['input_charset'])),
				"out_trade_no"	=> $out_trade_no,
				"subject"		=> $subject,
				"total_fee"		=> $total_fee,
				"show_url"		=> $show_url,
				"body"			=> $body,
		);
		 
		//建立请求
		vendor('alipay.alipay_submit');
		$alipaySubmit = new \AlipaySubmit($alipay_config);

		$html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认");
		return $html_text;
	}
	
	/**
	 * 订单支付成功时执行逻辑
	 * @param unknown $order_id
	 */
	public static function orderPaymentSuccess($order_id, $params, $user){
		//订单校验，防止重复通知
		$order_info_en = M('orderInfo', '', 'DB_trade')->where("order_id='%s'", $order_id)->find();
		
		
		if(empty($order_info_en)){
			return;
		}
		
		if($order_info_en['payment_status'] == 1){
			return;
		}
		
		//1. 更新order_info
		$update_orderInfo_en = array(
				'payment_status'=> 1,
				'actual_payment'=> $params['total_fee'],
				'order_status'	=> 22,
		);
		M('orderInfo', '', 'DB_trade')->where("order_id='%s'", $order_id)->save($update_orderInfo_en);
		
		
		//2.写入order_status_change_log begin
		$order_status_change_log = array(
				'order_id'		=> $order_id,
				'order_status'	=> 22,
				'order_status_text'	=> '已支付',
				'remark'		=> '',
				'create_user'	=> $user,
				'create_date'	=> date("y-m-d H:i:s", time()),
		);
		M('orderStatusChangeLog', '', 'DB_trade')->add($order_status_change_log);
		
		
		//3. 更新order_payment
		$update_orderPayment_en = array(
				'payment_status'=> 1,
				'actual_payment'=> $params['total_fee'],
				'payment_date'	=> date("y-m-d H:i:s", time()),
		);
		M('orderPayment', '', 'DB_trade')->where("order_id='%s'", $order_id)->save($update_orderPayment_en);
		
		//4. 更新promoter_order
		$update_promoter_order_en = array(
				'payment_status'=> 1,
				'order_status'	=> 22,
		);
		M('promoterOrder')->where("order_id='%s'", $order_id)->save($update_promoter_order_en);
	}
	
	
}